package com.heima.behavior.service.impl;

import java.util.Date;

import com.alibaba.fastjson.JSON;
import com.heima.behavior.service.ApReadBehaviorService;
import com.heima.model.behavior.dtos.ApReadBehavior;
import com.heima.model.behavior.dtos.ReadBehaviorDTO;
import com.heima.model.common.constants.article.HotArticleConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.mess.app.NewBehaviorDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class ApReadBehaviorServiceImpl implements ApReadBehaviorService {

    @Autowired
    MongoTemplate mongoTemplate;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Override
    public ResponseResult readBehavior(ReadBehaviorDTO dto) {
        //1. 校验参数 文章id必须传 注解

        //2. 根据登录用户id 或 设备id查询行为实体数据(阅读操作可不登录)
        Query query = Query.query(Criteria.where("articleId").is(dto.getArticleId()));
        ApReadBehavior behavior = mongoTemplate.findOne(query, ApReadBehavior.class);
        //3. 判断阅读行为是否存在
        if (behavior != null) {
            //4. 存在  将阅读行为的count字段加1 并修改
            Short count = behavior.getCount();
            behavior.setCount((short) (count+1));
            behavior.setCreatedTime(new Date());
            mongoTemplate.save(behavior);
        } else {
            //5. 不存在  创建阅读行为 并初始化count字段值为 1
            // 设配id TODO 没测
            ApReadBehavior apReadBehavior = new ApReadBehavior();
            apReadBehavior.setEntryId(String.valueOf(dto.getEquipmentId()));
            apReadBehavior.setArticleId(dto.getArticleId());
            apReadBehavior.setCount((short) 1);
            apReadBehavior.setCreatedTime(new Date());
            mongoTemplate.insert(apReadBehavior);
        }

        NewBehaviorDTO behaviorDTO = new NewBehaviorDTO();
        behaviorDTO.setType(NewBehaviorDTO.UpdateArticleType.VIEWS);
        behaviorDTO.setArticleId(dto.getArticleId());
        behaviorDTO.setAdd(1);
        rabbitTemplate.convertAndSend(HotArticleConstants.HOT_ARTICLE_SCORE_BEHAVIOR_QUEUE
                , JSON.toJSONString(behaviorDTO));
        log.info("消息发送成功==> 文章阅读行为 消息:{}",behaviorDTO);

        return ResponseResult.okResult();
    }
}
